﻿using System.Collections;
using UnityEngine;
using Random = UnityEngine.Random;

public class EniCreater : MonoBehaviour
{
    // 敌人生成用到的配置
    [SerializeField]
    Vector3 center = Vector3.zero;
    float offset = 24;
    public int count = 20;
    [Header("怪兽生成的间隔")]
    public float duration = 1f; // 怪兽生成的间隔,代码设计原因，该数值需要提前设定OK

    //塔相关配置
    public GameObject tower;
    [SerializeField]
    private float 规避距离=3f;

    private void Awake()
    {
        if (!tower)
        {
            tower = GameObject.Find("Tower");
        }
    }

    void Start()
    {
        StartCoroutine(EnemyRandomSpawn());
    }


    private IEnumerator EnemyRandomSpawn()
    {
        var delay = new WaitForSeconds(duration);
        while (count > 0)
        {
            GameObject go = Resources.Load<GameObject>("Prefabs/SZ");
            go = Instantiate(go);
            Vector3 pos = GetEnemyPosition();
            go.transform.position = pos;
            count--;
            yield return delay;
        }
        Debug.Log($"{nameof(EniCreater)}: 已经达到设定的怪物数量，请按 R 键重新开始怪物的生成");
    }

    private void Update()
    {
        // 用于重置怪兽的生成
        if (Input.GetKeyDown(KeyCode.R)&&count<=0)
        {
            count = 20;
            StartCoroutine(EnemyRandomSpawn());
        }
    }

    /// <summary>
    /// 获取怪兽随机生成的位置
    /// </summary>
    /// <returns>怪兽位置</returns>
    private Vector3 GetEnemyPosition()
    {
        var pos = Vector3.zero;
        var count = 0; //调试用，确认砸脸上的频率
        do
        {
            pos = new Vector3(Random.Range(center.x - offset, center.x + offset), 0, Random.Range(center.z - offset, center.z + offset));
            count++;
            if (count>1) //代表生成的怪物离塔的距离很近，在设定的规避范围内
            {
                count =0;
                Debug.Log($"{nameof(EniCreater)}:  怪物生成砸脸上了！");
            }
        } while (Vector3.Distance(pos,tower.transform.position)<规避距离);
        return pos;
    }
}
